<?php

namespace app\codekey\server;

use think\Db;
use app\common\server\Service;
use app\codekey\model\UserGroupCodekey as UserGroupCodekeyModel;
use app\codekey\validate\Codekey as CodekeyValidate;
use app\user\model\User as UserModel;
use app\user\model\UserGroup as UserGroupModel;

class Codekey extends Service
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->serviceKey) || empty($this->serviceKey) || cache('serviceKey') != $this->serviceKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 712]));
        }
        $this->UserGroupCodekeyModel = new UserGroupCodekeyModel();
        $this->UserModel = new UserModel();
        $this->CodekeyValidate = new CodekeyValidate();
        $this->UserGroupModel = new UserGroupModel();
    }

    public function useCodekey($data, $user)
    {
        if ($this->CodekeyValidate->check($data) !== true) {
            $this->error = $this->CodekeyValidate->getError();
            return false;
        }
        $this->UserGroupCodekeyModel->startTrans();

        // 校验卡密
        $code = $this->UserGroupCodekeyModel->where(['codekey' => $data['code']])->find();
        if (!$code) {
            // 未找到兑换码
            $this->error = "轻点啊喂！(ノ｀Д)ノ";
            return false;
        }
        // 是否过期
        if ($code['exp_time'] > 0 && $code['exp_time'] < time()) {
            // 已过期
            $this->error = "轻点啊喂！！(ノ｀Д)ノ";
            return false;
        }
        // 若已使用或过期，是否可复用
        if ($code['status'] > 0 && $code['code_type'] == 1) {
            // 已使用
            $this->error = "轻点啊喂！！！(ノ｀Д)ノ";
            return false;
        }
        // 可复用，是否超出可用次数
        if ($code['code_type'] == 2 && $code['used_num'] > $code['use_num']) {
            // 超出可用次数
            $this->error = "轻点啊喂！！！!(ノ｀Д)ノ";
            return false;
        }

        // 获取该卡密会员组有效天数
        $expire = $this->UserGroupModel->where('id', $code['group_id'])->value('expire');
        // 默认从当前时间算起
        $start_time = date("Y-m-d H:i:s");
        // 如果已开通会员
        if ($user['expire_time'] > 0) {
            // 如果是同种类，会员计算时间由现有到期时间开始计算
            if ($code['group_id'] == $user['group_id']) {
                $start_time = date("Y-m-d H:i:s", strtotime($user['expire_time']));
            }
        }
        $size = 1 * $expire;
        $todata = strtotime($start_time . '+' . $size . ' day');
        $update = [
            'group_id' => $code['group_id'],
            'expire_time' => $size > 0 ? $todata : 0
        ];

        $this->UserModel->startTrans();
        if (false === $this->UserModel->where('id', $user['id'])->update($update)) {
            $this->UserModel->rollBack();
            $this->error = '失败了o(一︿一+)o';
            return false;
        }

        $code->status = 1;
        $code->user_id = $user['id'];
        if ($code['code_type'] == 2) {
            $code->user_id = 0;
            $code->used_num = $code->used_num + 1;
        }
        if (false === $code->save()) {
            $this->UserGroupCodekeyModel->rollBack();
            $this->error = '失败了o(一︿一+)o';
            return false;
        }

        // 判断是否满足条件
        if (!empty($code['from_user']) && (int)config('codekey.share_switch') == 1) {
            $from_user = $this->UserModel->where('wxmp_openid', $code['from_user'])->find();
            if (!empty($from_user)) {
                $rules = config('codekey.rules');
                $rules = explode('-', $rules);
                $rules_group = config('codekey.rules_group');
                $rules_group = explode('-', $rules_group);
                $count = $this->UserGroupCodekeyModel->where('from_user', $code['from_user'])->count();
                $keys = -1;
                foreach ($rules as $key => $value) {
                    if ($count >= $value) {
                        $keys = $key;
                    }
                }
                $group_id = isset($rules_group[$keys]) ? $rules_group[$keys] : -1;
                if ($group_id > 0) {
                    // 获取会员组有效天数
                    $expire = $this->UserGroupModel->where('id', $group_id)->value('expire');
                    // 默认从当前时间算起
                    $start_time = date("Y-m-d H:i:s");
                    // 如果已开通会员
                    if ($from_user['expire_time'] > 0) {
                        // 如果是同种类，会员计算时间由现有到期时间开始计算
                        if ($group_id == $from_user['group_id']) {
                            $start_time = date("Y-m-d H:i:s", strtotime($from_user['expire_time']));
                        }
                    }
                    $size = 1 * $expire;
                    $todata = strtotime($start_time . '+' . $size . ' day');
                    $update = [
                        'group_id' => $group_id,
                        'expire_time' => $size > 0 ? $todata : 0
                    ];

                    if (false === $this->UserModel->where('id', $from_user['id'])->update($update)) {
                        $this->UserModel->rollBack();
                    }
                }
            }
        }



        $this->UserModel->commit();
        $this->UserGroupCodekeyModel->commit();
        return true;
    }
}
